package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @program: autoInsurance
 * @description:记录日志的工具类
 * @author: Mr.chen
 * @create: 2018-07-12 11:58
 **/
//每次访问方法都会进行日志的记录
public class SystemLogAspectUtil {

    @Setter
    private ISystemLogService systemLogService;

    public void write (JoinPoint jp) throws JsonProcessingException {


        //排除日志的新增, 即日志的操作不进行记录
        if(jp.getTarget() instanceof  ISystemLogService){
            return;
        }

        SystemLog log = new SystemLog();
        //设置用户
        Employee employee = UserContext.getEmployeeInSession();
        if (employee==null){
            return;
        }
        log.setOpuser(employee.getUsername());
        //设置操作时间
        log.setOpTime(new Date());
        //设置ip值
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.setOpip(request.getRemoteAddr());
        //获取操作的方法
        log.setFunction(jp.getSignature().getName());
//        设置方法参数
        log.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));
       systemLogService.save(log);
    }
}
